package com.macro.mall.portal.util;

import com.alibaba.fastjson.JSONObject;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.model.UmsMember;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class MemberUtil {
    @Autowired
    private UmsMemberMapper memberMapper;
    private static StringRedisTemplate stringRedisTemplate = null;

    public MemberUtil(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public UmsMember memeber(String token) {

        //根据token获取用户信息
        if (token.contains("Bearer ")) {
            token = token.replace("Bearer ", "").trim();
        }
        String member = stringRedisTemplate.opsForValue().get(token);
        //将用户信息转换成json对象
        JSONObject jsonObject = JSONObject.parseObject(member);
        //根据用户id获取用户信息
        UmsMember umsMember = memberMapper.selectByPrimaryKey(Long.valueOf(jsonObject.get("id").toString()));
        return umsMember;
    }

    public UmsMember getRequestMemeber(HttpServletRequest httpServletRequest) {
        String token = httpServletRequest.getHeader("Authorization");

        if (StringUtils.isBlank(token)) {
            return null;
        }
        return memeber(token);
    }
}
